<template>
  <public-dialog
    title="上传合同"
    v-model:visible="visible"
    confirm-button-title="确认"
    @on-confirm="onConfirm"
  >
    <template #default>
        <common-title title-name="表单信息"/>
        <el-form
                ref="formRef"
                label-width="100px"
                :model="form"
                :rules="rules"
        >
          <el-form-item label="上传类型" prop="type">
              <el-select
                      v-model="form.type"
                      @change="typeChange"
                      clearable>
                  <el-option label="新租/续租" :value="1"></el-option>
                  <el-option label="退租" :value="2"></el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="合同模版" v-if="form.type===1" prop="templateId">
            <el-select v-model="form.templateId" clearable>
                <el-option  v-for="(item,index) in state.xinZuList" :key="index" :label="item.templateName" :value="item.contractTemplateId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="退租合同" v-if="form.type===2" prop="contractId">
            <el-select v-model="form.contractId" clearable>
                <el-option v-for="(item,index) in state.tuiZuList" :key="index" :label="item.contractName" :value="item.contractId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="附件" prop="" required>
              <div>
                  <el-upload
                          ref="uploadRef"
                          :show-file-list="false"
                          action="#"
                          :http-request="uploadFile"
                          :on-remove="onRemove"
                  >
                  </el-upload>
                  <div class="d-flex flex-column" style="margin-top: -20px;">
                      <el-button
                              @click="uploadClick"
                              style="border-color: #FC7018;background-color:#fff8f6;color: #FC7018;">
                          <svg-icon icon-class="project-detail-icon-l-shangchuan" class="upload-icon m-r5"></svg-icon>
                          点击上传
                      </el-button>
                      <span style="color: #f12527;">(仅支持docx、pdf格式文档/限制上传数量:1)</span>
                  </div>
                  <div class="filesContent d-flex">
                      <div class="files_c_item m-b10" v-for="(v, i) in state.files" :key="i">
                          <el-icon
                                  color="#999999"
                                  class="icon_delete"
                                  @click="handelFileDelete(v.data)"
                          >
                              <CircleCloseFilled />
                          </el-icon>
                          <span class="icon_name">
                              <el-icon> <Document  /> </el-icon>
                              {{ v.data.fileName }}
                          </span>
                      </div>
                  </div>
              </div>
          </el-form-item>
        </el-form>
        <div class="d-flex a-center">
            <el-button type="primary" size="small" @click="addHandle">新增</el-button>
        </div>
        <el-divider/>
        <common-title title-name="合同列表"/>
        <public-table
                :header-cell-style="{'background':'#F5F5F5'}"
                :index="false"
                :is-paging="false"
                border
                :page="page"
                :tableData="form.list"
                :tableOption.sync="tableOption"
        >
            <template #buttons="scope">
                <el-button type="primary" size="small" @click="deleteContract(scope.row)">删除</el-button>
            </template>
        </public-table>
    </template>
  </public-dialog>
</template>

<script setup>
import PublicDialog from "@/components/PublicDialog.vue";
import {reactive, ref} from "vue";
import {ElForm, ElFormItem, ElSelect, ElOption, ElDivider, ElUpload, ElIcon, ElLoading, ElMessage} from "element-plus";
import {thorwLeaseApi,contractApi} from "@/api/coordination";
import PublicTable from "@/components/PublicTable.vue";
import CommonTitle from "@/components/CommonTitle.vue";
import {CircleCloseFilled, Document} from "@element-plus/icons-vue";
import {contractApi as contractApi2, fileControlApi} from "@/api/assets";
import {resetForm} from "@/common/utils/GlobalUtils";



const visible = ref(false);
const form = reactive({
    type:'',
    templateId:'',
    contractId:'',
    file:'',
    list:[]
});
const emits = defineEmits(['onSuccess']);
const state = reactive({
    xinZuList:[],
    tuiZuList:[],
    files:[]
});
const rules = reactive({
    type: [
        { required: true, message: '请选择上传类型', trigger: 'change' },
    ],
    templateId: [
        { required: true, message: '请选择合同模版', trigger: 'change' },
    ],
    contractId: [
        { required: true, message: '请选择合同', trigger: 'change' },
    ],
    /*file: [
        { required: true, message: '请上传附件', trigger: 'change' },
    ],*/
});


const page = reactive({
    total: 0,
    current: 1,
    size: 10
});
const tableData = ref([]);

const tableOption = ref([
    { label: '上传类型', prop: 'type',formatter:(val,row)=>{
            let arr = ['','新租/续租','退租'];
            return arr[val] || '-';
        } },
    { label: '合同模版', prop: 'contractTemplateId',formatter:(val,row)=>{
           if(!val)return  '-';
           let i = state.xinZuList.findIndex(x=>x.contractTemplateId===val);
           if(i!==-1){ return state.xinZuList[i].templateName;}
        } },
    { label: '合同',prop: 'contractId',formatter:(val,row)=>{
            if(!val)return  '-';
            let i = state.tuiZuList.findIndex(x=>x.contractId===val);
            if(i!==-1){ return state.tuiZuList[i].contractName;}
        }},
    { label: '附件名称', prop: 'fileName'},
    {
        label: '操作',
        slot: true,
        width: 100,
        overHidden:false,
        slotName: 'buttons',
        fixed: "right"
    }
]);

const formRef = ref(null);
/**
 * 新增
 */
const addHandle = () => {
    formRef.value.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            if(state.files.length===0){
                return ElMessage.warning('请上传附件!');
            }
            form.list.push(JSON.parse(JSON.stringify(state.files[0].data)));
            state.files = [];
            form.type = '';
            form.templateId = '';
            form.contractId = '';
            form.file = '';
            setTimeout(()=>{formRef.value.clearValidate();});
        } else {
            console.log('error submit!', fields)
        }
    })
}

/**
 * 分页查询合同模板列表
 * @param params
 */
const getContractTemplatesPage = (params) => {
    contractApi.getContractTemplatesPage(params).then(res=>{
        state.xinZuList = res.data.content;
    });
}

/**
 * 退租合同模版列表
 */
const getLeasingContractPage = () => {
    let getParams = {
        pageNum: 1,
        pageSize: 99999,
        param: {
            queryName: '',
        },
    };
    thorwLeaseApi.getLeasingContractPage(getParams).then((res) => {
        const { code, data } = res;
        if (code === '200') {
            state.tuiZuList = data.content;
        }
    });
};

/**
 *
 */
const typeChange = () => {
  form.templateId = '';
  form.contractId = '';
}

/**
 * 上传文件
 * @param file
 */
const uploadFile = (file) => {
    let uploadFile = new FormData()
    uploadFile.append('file', file.file)
    uploadFile.append('type ', form.type )
    uploadFile.append('templateId ', form.templateId)
    uploadFile.append('contractId ', form.contractId)

    const addTypeArray = file.file.name.split(".");
    const addType = addTypeArray[addTypeArray.length - 1]

    if(addType === "docx" || addType === "pdf"){
        const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        fileControlApi.uploadContractFile(uploadFile).then((res) => {
            if (res.code === '200') {
                loading.close()
                ElMessage.success('上传成功!')
                state.files.push({
                    data:res.data,
                    file:file.file
                });
                form.file = res.data.fileAddress;
            }else{
                loading.close()
                ElMessage.error('上传失败!')
            }
        });
    }else{
        ElMessage.error('请上传正确格式的文档!');
    }
}

const uploadRef = ref(null);

/**
 * 上传按钮被点击
 */
const uploadClick = () => {
    if(state.files.length===1){
        return ElMessage.warning('只能上传一个附件!');
    }
    formRef.value.validate((valid, fields) => {
        if (valid) {
            uploadRef.value.$el.querySelector('input').click();
        } else {
            console.log('error submit!', fields)
        }
    })
}

/**
 * 移除
 * @param uploadFile
 * @param uploadFiles
 */
const onRemove = (uploadFile,uploadFiles) => {
    uploadRef.value.clearFiles();
}


/**
 * 删除
 */
const handelFileDelete = (item) => {
    let i = state.files.findIndex((v) => v.fileUrlKey !== item.fileUrlKey);
    if(i!==-1){
        state.files.splice(i,1);
        ElMessage.success('删除成功!');
    }
}

/**
 *
 * @param row
 */
const deleteContract = (row) => {
  let i = form.list.findIndex(x=>x.associationId===row.associationId)
  if(i!==-1){
      form.list.splice(i,1);
  }
}

/**
 * 打开弹窗
 */
const openPopup = () => {
  resetForm(state);
  resetForm(form);
  visible.value = true;
  getContractTemplatesPage({
      pageNum:1,
      pageSize:99999
  });
  getLeasingContractPage();
}

/**
 * 确认
 */
const onConfirm = () => {
    if(form.list.length===0){
        return ElMessage.warning('合同列表不能为空,请上传合同信息!');
    }
    contractApi2.batchContract({
        fileVos:form.list
    }).then(res=>{
       if(res.code==='200'){
           visible.value = false;
           ElMessage.success('提交成功!');
           emits('onSuccess');
       }else{
           visible.value = false;
           ElMessage.error('提交失败!');
       }
    });
}

defineExpose({openPopup});
</script>

<style lang="scss" scoped>
.files_c_item {
  min-width: 120px;
  padding: 0 30px;
  position: relative;

  .icon_delete {
    position: absolute;
    top: -1px;
    right: 10px;
    cursor: pointer;
  }
  .icon_delete:hover {
    color: red;
  }

  .icon_name {
    color: #999;
    cursor: pointer;
  }
  .icon_name:hover {
    color: #fc7018;
  }
}
</style>
